<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title></title>
    <script src="js/mui.min.js"></script>
    <link href="css/mui.min.css" rel="stylesheet"/>

</head>
<body>
	<header class="mui-bar mui-bar-nav">
		<a class="mui-icon mui-action-menu mui-icon-arrowleft mui-pull-left" onclick="mui.back()"></a>
		<h1 class="mui-title">听说练习</h1>
	</header>
	<div class="mui-content">
	</div>
	
	<div class="mui-card">
		<!--页眉，放置标题-->
		<div class="mui-card-header" id="yemei">页眉</div>
		<!--内容区-->
		<div class="mui-card-content" id="jie">
			<audio src="#" id="audio"></audio>
			
		</div>
		<!--页脚，放置补充信息或支持的操作-->
		<div class="mui-card-footer" id="j">
			<button class="mui-btn mui-btn-outlined" id="audio_tai">录音状态</button>
			<button class="mui-btn mui-btn-outlined" id="audio_tai_time"></button>
		</div>
	</div>
	
	
	<script type="text/javascript" charset="utf-8">
		
	  	mui.init();
		mui.plusReady(function () {
		    var work_id = plus.webview.currentWebview().id 
			//getwork(work_id)
			//tts("hello")
			//var page = plus.webview.getWebviewById(String(work_id));
			//page.reload();
			//tts("hello")
			
			workfor()
			// luyin_start(5);
			// 调用录音功能
			
			
			
			
			
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
			
			
			
			
			
			//录音初始化
			var recorder;
			function onPlusReady() {
			    recorder = plus.audio.getRecorder(); // 获取录音对象
			    console.log("录音对象初始化成功");
			}
			
			//启动录音
			function startRecord() {
				onPlusReady()
				document.getElementById("audio_tai").innerText = "录音中...";
			    // 检查录音对象是否初始化成功
			    if (!recorder) {
			        console.error("录音对象未初始化，请确保在plusready事件后调用");
			    }
			    // 开始录音
			    recorder.record({filename:"_doc/audio/recording", format:"wav"}, function (path) {
					upload_recording(path)
			        console.log("录音成功，文件路径为：", path);
			    }, function (e) {
					mui.toast("录音失败："+e.message);
			        console.error("录音失败：", e.message);
			    });
			}
			 
			 //结束录音
			function stopRecord() {
			    if (!recorder) {
			        console.error("录音对象未初始化，请确保在plusready事件后调用");
			        return;
			    }
			    recorder.stop(); // 停止录音
			    console.log("录音已停止");
			}
			
	
			// 上传录音识别后保存
			function upload_recording(filePath) {
				
				var url = plus.storage.getItem("yy_server");
				var upload = plus.uploader.createUpload(url+"upload",{priority:1},function(t,to){
					// addEventListener(StaticRange)
					document.getElementById("audio_tai").innerText = "识别成功：" + upload.responseText;
					console.log(upload.responseText);
					var work_id = plus.webview.currentWebview().id 
					var page = plus.webview.getWebviewById(String(work_id));
					console.log("上传");
					if (to == 200){
						var data = JSON.parse(plus.storage.getItem("works"));
						var mubiao = String(plus.storage.getItem("mubiao"));
						plus.storage.setItem(String(mubiao),upload.responseText)
						console.log(mubiao+" = "+upload.responseText);
						plus.storage.setItem("mubiao",data["questions"][mubiao]["next"]);
						page.reload();
					}else{
						console.log("识别失败");
						mui.toast("识别失败，请重新录音");
					}
					
				})
				upload.addFile(filePath,{key:"file_audio"});
				upload.start();
			}

			
			
			//定时器
			function countdown(seconds,fun) {
				document.getElementById("audio_tai_time").innerText = seconds + "s";
				console.log(seconds);
				if (seconds === 0) {
					console.log("倒计时结束！");
					fun()
					return;
				}
				
				setTimeout(function(){
					countdown(seconds - 1,fun); // 递归调用
				}, 1000);
			}
			
			
			
			//获取作业
			function workfor(){
				
				if (plus.storage.getItem("mubiao") == "kai"){
					var id = plus.storage.getItem("mubiao_id");
					var page = plus.webview.getWebviewById(String(id));
					getwork(String(id),function(){
						plus.storage.setItem("mubiao","t1")
						console.log("ssssssssssssssssss");
						page.reload();
					})
				}
				//打开结束页面
				else if (plus.storage.getItem("mubiao") == "end"){
					mui.openWindow({
						url: 'muend.html',
						id: 'end'
					})
				}
				
				else{
					var data = JSON.parse(plus.storage.getItem("works"));
					//console.log(JSON.stringify(data));
					var mubiao = String(plus.storage.getItem("mubiao"))
					var mu = document.getElementById("yemei")
					var jie = document.getElementById("jie")
					var t = data["questions"][mubiao]
					console.log(JSON.stringify(t));
					mu.innerText = data["questions"][mubiao]["mu"];
					tts(String(data["questions"][mubiao]["nian"]),function(){
						luyin_start(Math.floor(parseInt(data["questions"][mubiao]["time"])))
					})
					
				}
				
			}
			
			//开始录音
			function luyin_start(time) {
				
				startRecord();
				countdown(time,function(){
					stopRecord();
					document.getElementById("audio_tai").innerText = "录音完成";
				})
				
			}
			
			
			
			
			//获取作业
			function getwork(id,fun){
				var rw_server = plus.storage.getItem("rw_server");
				var class_id = plus.storage.getItem('class_id');
				var url = String(rw_server) + "exampapers/" + String(class_id) + "/" + String(id)
				console.log(url);
				fetch(url)
					.then(response => response.json())
					.then(data => {
						//console.log(JSON.stringify(data)); 
						plus.storage.setItem("works",JSON.stringify(data))
						fun()
					})
			}
			
			
			//语音合成
			function tts(chat,fun){
				console.log("tts");
				
				var rw_server = plus.storage.getItem("rw_server");
				var url = String(rw_server) + "tts/" + String(chat);
				fetch(url)
					.then(response => response.json())
						.then(data => {
							console.log(JSON.stringify(data)); 
							var audio_url = data["tts"]
							//console.log(audio_url);
							audio = audio_url;
							document.getElementById("audio").src = audio
							document.getElementById("audio").play()
							const audioElement = document.getElementById("audio");
								if (audioElement) {
									audioElement.addEventListener("ended", function () {
										console.log("播放完成");
										fun(); // 如果你有其他函数需要调用，可以在这里调用
									});
								}
						})
				
			}
			
		})
		
		
	</script>
</body>
</html>